<?php
// +-------------+------------------+------+-----+---------+----------------+
// | Field       | Type             | Null | Key | Default | Extra          |
// +-------------+------------------+------+-----+---------+----------------+
// | id          | int(11)          | NO   | PRI | NULL    | auto_increment |
// | title       | varchar(30)      | YES  |     |         |                |
// | rules       | varchar(250)     | YES  |     |         |                |
// | sort        | int(11)          | YES  |     | 0       |                |
// | status      | tinyint(1)       | YES  |     | 1       |                |
// | member_id   | int(11) unsigned | YES  |     | 0       |                |
// | is_super    | tinyint(1)       | YES  |     | 0       |                |
// | create_time | int(11) unsigned | YES  |     | 0       |                |
// | update_time | int(11) unsigned | YES  |     | 0       |                |
// +-------------+------------------+------+-----+---------+----------------+
namespace app\admin\model;

use think\facade\Config;
use app\admin\model\Base;
use app\admin\validate\AuthGroup as Validate;
class AuthGroup extends Base
{
    /**
     * has many Members
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-08
     * @return   [type]             [description]
     */
    public function members()
    {
        return $this->hasMany('Member', 'group_id');
    }

    /**
     * has many AuthGroupAccess
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-08
     * @return   [type]             [description]
     */
    public function accesses()
    {
        return $this->hasMany('AuthGroupAccess', 'group_id');
    }

    /**
     * 列表搜索方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $param     搜索参数
     * @param    integer            $page_rows 每页显示数量
     * @return   Paginate
     */
    public function minePaginate($param, $page_rows = 0)
    {
        if($page_rows < 1){
            $page_rows = Config::get('paginate.list_rows');
        }

        $map = $this->parseSearchParam($param);

        $config = [];
        $config["query"] = $param;
        // 分页参数名是 page ，paginate方法内有获取到该值的方法
        $page = 1;
        if(isset($param["page"])){
            $page = intval($param["page"]);
        }
        $config["page"] = $page;

        $order_type = '';
        if(isset($param['order'])){
            $order_type = $param['order'];
        }
        $order_str = $this->queryOrderStr($order_type);
        $paginate = $this->where($map)->order($order_str)->paginate($page_rows, false, $config);
        return $paginate;
    }

    /**
     * 下拉框选择列表
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    boolean            $only_active 是否只显示【启用】记录
     * @return   array                           AuthGroup List
     */
    public function selectOptions($only_active = true)
    {
        $map = [];
        if($only_active){
            $map['status'] = true;
        }
        $order_str = $this->queryOrderStr();
        $list = $this->field(array('id', 'title'))->order($order_str)->select();
        return $list;
    }

    /**
     * 添加或更新记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $data 表单提交数据
     * @param    integer            $id   主键ID
     * @return   array                    更新结果
     */
    public function createOrUpdate($data, $id = 0)
    {
        $res = ['status' => false, 'data' => [], 'msg' => "添加或更新角色组失败"];
        if($id > 0){
            $data['id'] = $id;
        }

        $validate = new Validate;
        if(!$validate->check($data)){
            $res['msg'] = $validate->getError();
            return $res;
        }

        if(isset($data['id']) && $data['id'] > 0){
            $item = $this->where('id', $data['id'])->find();
        }else{
            $item = NULL;
        }
        if(empty($item)){
            $is_update = false;
            $msg = '添加用户角色组成功';
        }else{
            $is_update = true;
            $data['id'] = $item['id'];
            $msg = '更新用户角色组成功';
        }
        $this->data($data)->isUpdate($is_update)->allowField(true)->save();

        $res = [
            'status' => true,
            'msg' => $msg,
            'data' => ['id' => $this->id],
        ];
        return $res;
    }

    /**
     * 按标题创建或更新记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $data  更新数据
     * @return   array                     [description]
     */
    public function findOrCreateByTitle($data)
    {
        $res = ['status' => false, 'data' => [], 'msg' => "添加或更新管理员组失败"];
        if(!isset($data['title'])){
            $res['msg'] = '管理员组名不能为空';
            return $res;
        }

        $item = $this->where('title', $data['title'])->find();
        if(!empty($item)){
            $res = [
                'status' => true,
                'data' => ['id' => $item['id']],
                'msg' => '查找到该管理员组记录',
            ];
            return $res;
        }
        return $this->createOrUpdate($data);
    }

    /**
     * 删除管理员组
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-08
     * @param    [type]             $id [description]
     * @return   [type]                 [description]
     */
    public function deleteItem($id)
    {
        $res = ['status' => false, 'data' => [], 'msg' => '删除管理员组失败'];
        $item = $this->where('id', $id)->find();
        if(empty($item)){
            $res = ['status' => true, 'data' => [], 'msg' => '删除管理员组成功'];
            return $res;
        }else if($item['is_super']){
            $res['msg'] = '不能删除超级管理员组';
            return $res;
        }else if($item->members->count()){
            $res['msg'] = '不能删除有关联用户的群组';
            return $res;
        }else if($item->accesses->count()){
            $res['msg'] = '不能删除有关联用户绑定的群组';
            return $res;
        }

        if($this->where('id', $id)->delete()){
            $res = [
                'status' => true,
                'msg' => '删除管理员组成功',
                'data' => ['id' => $id],
            ];
        }else{
            $res['msg'] = '未找到删除记录';
        }

        return $res;
    }

    /**
     * 转化查询条件
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    array              $param [description]
     * @return   array                     [description]
     */
    private function parseSearchParam($param)
    {
        $map = [];
        foreach ($param as $key => $value) {
            if(!is_array($value)){
                $value = trim($value);
            }
            switch ($key) {
            case "keyword":
                if(empty($value)){
                    continue;
                }else{
                    $keyword = "%{$value}%";
                }
                $map[] = ["title", "like", $keyword];
                break;
            }
        }
        return $map;
    }

    /**
     * 搜索排序方式
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @param    string             $param 排序方式
     * @return   string                    [description]
     */
    protected function queryOrderStr($order_type = '')
    {
        return 'sort ASC, id ASC';
    }

    /**
     * 唯一值字段列表
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2018-06-07
     * @return   array             [description]
     */
    protected function uniqueFileList()
    {
        return ['title'];
    }
}
